package service

import (
	"github.com/astaxie/beego/orm"
	"net/url"
	"strconv"
	"xianzhi/models"
)

// 获取推送时间信息
func GetPushTimeInfo(p map[string]interface{}) *models.PushTime {
	o := orm.NewOrm()
	pushTime := &models.PushTime{}
	qs := o.QueryTable("PushTime")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	qs.One(pushTime)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		if pushTime.Id > 0 {
			pushTime.StatusShow = models.PushTimeStatus[pushTime.Status]
		}
	}
	return pushTime
}

// 添加推送时间
func AddPushTime(input url.Values) (int64, error) {
	o := orm.NewOrm()
	pushTime := &models.PushTime{}
	if _, ok := input["month"]; ok {
		pushTime.Month = input["month"][0]
	}
	if _, ok := input["publication"]; ok {
		pushTime.Publication = input["publication"][0]
	}
	if _, ok := input["num"]; ok {
		pushTime.Num, _ = strconv.Atoi(input["num"][0])
	}
	if _, ok := input["status"]; ok {
		pushTime.Status, _ = strconv.Atoi(input["status"][0])
	}
	return o.Insert(pushTime)
}

// 修改推送时间信息
func EditPushTime(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("PushTime").Filter("id", input["id"][0]).Update(p)
}

// 获取推送时间列表
func GetPushTimeList(p map[string]interface{}) (int64, []*models.PushTime) {
	var pushTimeList []*models.PushTime
	o := orm.NewOrm()
	qs := o.QueryTable("PushTime")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["month"]; ok {
		qs = qs.Filter("month__contains", p["month"])
	}
	if _, ok := p["publication"]; ok {
		qs = qs.Filter("publication__contains", p["publication"])
	}
	if _, ok := p["status"]; ok {
		qs = qs.Filter("status", p["status"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.OrderBy("-id").All(&pushTimeList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, pushTime := range pushTimeList {
			pushTime.StatusShow = models.PushTimeStatus[pushTime.Status]
		}
	}
	return totalCount, pushTimeList
}
